/**
 * 1336指令余额扣除测试脚本
 * 专门测试大小玩法下注后余额是否正确扣除
 */

const Code1451Tester = require('../test-code-1451.js');

class BalanceDeductionTester extends Code1451Tester {
    constructor() {
        super();
        this.testName = '1336指令余额扣除测试';
    }

    // 重写测试流程，专注于余额扣除测试
    async runTest() {
        console.log('🎲 开始1336指令余额扣除测试...\n');
        console.log('测试目标：验证大小玩法下注后余额是否正确扣除\n');

        try {
            // 1. HTTP登录
            await this.testHttpLogin();

            // 2. 建立WebSocket连接
            await this.testWebSocketConnection();

            // 3. 查询角色列表
            await this.testQueryCharacters();

            // 4. 如果没有角色，先创建角色
            if (this.characters.length === 0) {
                await this.testCreateCharacter();
                await this.testQueryCharacters();
            }

            // 5. 选择角色
            await this.testSelectCharacter();

            // 6. 测试1336指令余额扣除
            await this.testCode1336DiceBet();

            // 7. 断开连接
            await this.testDisconnect();

            // 输出测试结果
            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    // 重写1336测试，增加更详细的余额验证
    async testCode1336DiceBet() {
        console.log('\n🎲 测试1336指令 - 大小玩法下注并验证余额扣除...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('1336指令测试', false, 'WebSocket未连接');
            return;
        }

        if (!this.selectedCharacter) {
            this.addTestResult('1336指令测试', false, '未选择角色');
            return;
        }

        return new Promise(async (resolve) => {
            let responseReceived = false;
            let initialBalance = null;

            // 获取下注前余额
            console.log('💰 获取下注前余额...');
            initialBalance = await this.getCurrentBalance();

            if (!initialBalance) {
                this.addTestResult('1336指令测试', false, '无法获取下注前余额');
                resolve();
                return;
            }

            console.log(`📊 下注前余额 - 金币: ${initialBalance.gold}, 银两: ${initialBalance.silver}`);

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1336) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 1336指令下注成功');

                            // 等待服务器处理下注
                            setTimeout(async () => {
                                // 获取下注后余额
                                console.log('💰 获取下注后余额...');
                                const newBalance = await this.getCurrentBalance();

                                if (newBalance) {
                                    const goldDiff = initialBalance.gold - newBalance.gold;
                                    const silverDiff = initialBalance.silver - newBalance.silver;

                                    console.log(`📊 下注后余额 - 金币: ${newBalance.gold}, 银两: ${newBalance.silver}`);
                                    console.log(`📉 余额变化 - 金币: -${goldDiff}, 银两: -${silverDiff}`);

                                    // 详细验证余额扣除
                                    this.validateBalanceDeduction(initialBalance, newBalance, goldDiff, silverDiff);
                                } else {
                                    this.addTestResult('1336指令测试', false, '无法获取下注后余额');
                                }
                                resolve();
                            }, 2000);
                        } else {
                            console.log(`❌ 1336指令下注失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('1336指令测试', false, message.msg || '下注失败');
                            resolve();
                        }
                    }
                } catch (error) {
                    console.error('❌ 1336指令响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('1336指令测试', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送1336下注请求 - 下注100金币押"大"
            const betData = {
                c: 1336,
                d: {
                    type: "3", // 大金子 (对应BetType.BIG = 1, CurrencyType.GOLD = 1)
                    bet: 100,  // 下注100金币
                    characterId: this.selectedCharacter.id
                }
            };

            console.log(`📤 发送1336下注请求:`, JSON.stringify(betData, null, 2));
            this.ws.send(JSON.stringify(betData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('1336指令测试', false, '请求超时');
                    resolve();
                }
            }, 15000);
        });
    }

    // 验证余额扣除逻辑
    validateBalanceDeduction(initialBalance, newBalance, goldDiff, silverDiff) {
        console.log('\n🔍 余额扣除验证分析:');
        console.log('='.repeat(40));

        // 验证金币扣除
        if (goldDiff > 0) {
            console.log(`✅ 金币扣除正常: -${goldDiff}`);
            if (goldDiff === 100) {
                console.log('✅ 金币扣除金额正确: 100金币');
            } else {
                console.log(`⚠️ 金币扣除金额异常: 期望100，实际${goldDiff}`);
            }
        } else if (goldDiff === 0) {
            console.log('⚠️ 金币未扣除');
        } else {
            console.log(`❌ 金币异常增加: +${Math.abs(goldDiff)}`);
        }

        // 验证银两扣除
        if (silverDiff > 0) {
            console.log(`✅ 银两扣除正常: -${silverDiff}`);
        } else if (silverDiff === 0) {
            console.log('✅ 银两未扣除 (符合预期，下注的是金币)');
        } else {
            console.log(`❌ 银两异常增加: +${Math.abs(silverDiff)}`);
        }

        // 总体验证
        if (goldDiff >= 0 && silverDiff >= 0) {
            if (goldDiff === 100 && silverDiff === 0) {
                console.log('🎉 余额扣除验证完全通过！');
                this.addTestResult('1336指令测试', true, `下注成功，金币扣除: ${goldDiff}, 银两扣除: ${silverDiff}`);
            } else if (goldDiff > 0 || silverDiff > 0) {
                console.log('✅ 余额扣除验证基本通过');
                this.addTestResult('1336指令测试', true, `下注成功，金币扣除: ${goldDiff}, 银两扣除: ${silverDiff}`);
            } else {
                console.log('⚠️ 余额未发生变化');
                this.addTestResult('1336指令测试', true, '下注成功，但余额未变化');
            }
        } else {
            console.log('❌ 余额扣除验证失败：余额异常增加');
            this.addTestResult('1336指令测试', false, '余额异常增加');
        }

        console.log('='.repeat(40));
    }
}

// 运行测试
async function main() {
    const tester = new BalanceDeductionTester();
    await tester.runTest();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = BalanceDeductionTester; 